package com.lego.jbv;

import java.io.File;

import lejos.nxt.Button;
import lejos.nxt.ButtonListener;
import lejos.nxt.LCD;
import lejos.nxt.LightSensor;
import lejos.nxt.MotorPort;
import lejos.nxt.SensorPort;
import lejos.nxt.Sound;
import lejos.nxt.SoundSensor;
import lejos.nxt.addon.RCXMotor;

public class ex1runner {

	private static double leftPower = 0;
	private static double rightPower = 0;
	private static double minPower = 0;
	private static double maxPower = 100;
	private static int minMic = 0;
	private static int maxMic = 100;

	private static BTController bt;
	private static final int sampleRate = 10;
	private static SoundSensor mic;
	private static RCXMotor rx;
	
	
	public static void main(String[] args) {
		rx = new RCXMotor(MotorPort.A);
		
		mic = new SoundSensor(SensorPort.S2);

		init();

		connect();
		LCD.drawString("Normal/raw:", 0, 0);
		LCD.drawString("minmax:", 0, 4);
		while (true) {
			for (int i = 0; i < sampleRate; i++) {
				modifyMotorPower(mic.readValue());
				Car.drive((int)leftPower, (int)rightPower);

				sleep(10);
			}

			bt.send(minMic, maxMic);

		}
	}

	private static void init() {
		Button.ESCAPE.addButtonListener(new ButtonListener() {

			@Override
			public void buttonReleased(Button b) {
				shutDown();
				LCD.clear();
				System.exit(0);
			}

			@Override
			public void buttonPressed(Button b) {
				// TODO Auto-generated method stub

			}
		});
	}

	private static void shutDown() {
		bt.stop();
		Sound.playSample(new File("exit.wav"));
		sleep(1000);
	}

	private static void modifyMotorPower(int input) {
		rx.setPower(input);
		maxPower = bt.getMaxMotorPower();
		minPower = bt.getMinMotorPower();
		leftPower = (((double)(input/100d))*(maxPower-minPower))+minPower;
		
		int direction = (bt.getGotoLight())?1:-1;
		leftPower *= direction;
		
		rightPower = leftPower;
		
		LCD.drawInt((int)leftPower, 5, 0, 1);
		LCD.drawInt(input, 5,5, 1);
		LCD.drawInt((int)minPower, 5, 0, 5);
		LCD.drawInt((int)maxPower, 5, 7, 5);
	}

	private static void sleep(int ms) {
		try {
			Thread.sleep(ms);
		} catch (Exception e) {
		}
	}

	private static void connect() {
		bt = new BTController();
		bt.setDaemon(true);
		bt.start();
	}

}
